import { setCookie, getCookie } from '@/utils/common'
import { login } from '@/api/login'

export default {
    namespaced: true,
    state: {
        userName: getCookie('userName'),
        token: getCookie('token'),
        tokens: getCookie('tokens')
    },
    mutations: {
        SET_USER_INFO(state, userInfo) {
            state.userName = userInfo?.userName;
            setCookie('userName', userInfo?.userName)
        },
        SET_TOKEN(state, { accessToken, refreshToken }) {
            state.token = accessToken;
            setCookie('token', accessToken)
            if (refreshToken !== undefined) {
                state.tokens = refreshToken;
                setCookie('tokens', refreshToken)
            }
        }
    },
    actions: {
        // 用户登录
        login({ commit }, userInfo) {
            const userName = userInfo.userName;
            const userPassword = userInfo.userPassword;
            return new Promise((resolve, reject) => {
                login(userName, userPassword).then(res => {
                    let data = res.data;
                    commit('SET_TOKEN', { 'accessToken': data.token, 'refreshToken': data.token })
                    commit('SET_USER_INFO', {
                        userName: data.userName
                    })
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 退出登录
        logOut({ commit }) {
            commit('SET_USER_INFO');
            commit('SET_TOKEN', { 'accessToken': '', 'refreshToken': '' });
        },
        // token过期重新获取
        refreshToken({ commit }) {
            return new Promise((resolve, reject) => {
                commit('SET_TOKEN', { 'accessToken': token })
                resolve()
            })
        }
    }
}